<?php

/*
Zoo Management Simulation
This file determines the admin page actions by deleting, adding and editing cages
Extra functionality includes locking all doors and setting the maximum cages
*/

include("dbconnect.php");
$cageid = $_REQUEST['id'];
$numentries = $_REQUEST['numberofentries'];
$sql = 'SELECT Cage_Id FROM cage';
$result = mysql_query($sql);

if ($_REQUEST['submit'] == "Add cage")
{
	header('Location: addCage.html');
}

if ($_REQUEST['submit'] == "Delete")
{
	$deleteentrysql = "DELETE FROM `entry` WHERE Cage_Id='".$cageid."'";
	$deleteresult = mysql_query($deleteentrysql);

	$deletesql = "DELETE FROM `cage` WHERE Cage_Id='".$cageid."'";
	$deleteresult = mysql_query($deletesql);
	header('Location: index.php');
}

if ($_REQUEST['submit'] == "Edit")
{
	header("Location: editCage.php?cageid=".$cageid."&cagenumber=".$numentries);
	}

if ($_REQUEST['submit'] == "Lock all doors")
{
	$locksql = "UPDATE `entry` SET `Entry_Status`='Closed' WHERE `Entry_Status`!='Closed'";
	$lockresult = mysql_query($locksql);
	header('Location: index.php');
}

if ($_REQUEST['submit'] == "Set maximum number of cages")
{
	$maxCage = $_REQUEST['maximum'];
	if ($maxCage < mysql_num_rows($result)){
		echo "Please delete rows then set the maximum number of rows<br />";
		echo "<a href='index.php'>Return to administrator page</a>";
	}
	elseif ($maxCage == mysql_num_rows($result)){
		echo "The maximum amount is already set<br />";
		echo "<a href='index.php'>Return to administrator page</a>";
	}
	else {
		while ($maxCage >= $result){
			$maxidsql = "SELECT max(Cage_Id)+1 FROM cage";
			$maxidresult = mysql_query($maxidsql);
			while(($row = mysql_fetch_row($maxidresult)) !== FALSE)
				{
					$maxid = $row[0];
				}
			$maxcagesql = "INSERT INTO `cage`(`Cage_Id`) VALUES (".$maxid.")";
			$maxcageresult = mysql_query($maxcagesql);
			if ($maxcageresult == FALSE){
     			echo "<p>Unable to execute the query.</p>";
           		echo "<p>Error code " . mysql_errno($DBConnect).": " . mysql_error($DBConnect) . "</p>";
			echo "<a href='index.php'>Return to administrator page</a>";
				}
			else {
				echo "<p>Successfully added to Cage table.</p>";
				header('Location: index.php');
			}
			$result = mysql_query($sql);
		}
	}
}
	?>